new Vue({
    el: '#header',
    data: {
        userAvatarUrl: '', // 用户头像URL
        username: '' // 用户名
    },
    methods: {
        // 获取用户个人信息
        fetchUserInfo() {
            const token = localStorage.getItem('token') || ''; // 从本地存储获取token
            if (!token) {
                console.warn('未找到用户token，无法加载用户信息。');
                this.userAvatarUrl = '/photo/Profile picture/微信图片_20240927140746.jpg';
                this.username = '请登录';
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/user/findUserById',
                type: 'Post',
                dataType: 'json',
                headers: {
                    'token': token
                },
                data: {
                    userId: localStorage.getItem('userId') || ''
                },
                success: (response) => {
                    if (response.code === 200) {
                        this.username = response.data.userName;
                        this.userAvatarUrl = 'http://localhost:8080' + response.data.avatar;
                        console.log(this.username);
                        console.log(this.userAvatarUrl);

                    }
                },
                error: function (xhr, status, error) {
                    console.error('加载用户信息失败:', error, xhr.responseText);
                    if (xhr.status === 401) {
                        // token过期或无效
                        logout(); // 调用 logout 函数清除存储并跳转
                    } else {
                        alert('加载用户信息失败，请稍后重试');
                    }
                }
            });
        },
        //点击退出跳转到登录页面
        logout() {
            localStorage.removeItem('token'); // 删除token
            localStorage.removeItem('userId'); // 删除userId
            window.location.href = '/login.html'; // 跳转到登录页面
        }
    },
    created() {
        this.fetchUserInfo();
    },
})